import { fileURLToPath, URL } from 'node:url';

import { PrimeVueResolver } from '@primevue/auto-import-resolver';
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { defineConfig, loadEnv } from 'vite';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
    // 加载环境变量
    const env = loadEnv(mode, process.cwd(), '');

    return {
        optimizeDeps: {
            noDiscovery: true,
            include: [
                'vue',
                'vue-router',
                'primevue/config',
                'primevue/toastservice',
                'primevue/confirmationservice'
            ]
        },

        plugins: [
            vue(),
            Components({
                resolvers: [PrimeVueResolver()],
                dts: true, // 生成类型定义文件
                directoryAsNamespace: true
            })
        ],

        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            }
        },

        // 开发服务器配置
        server: {
            port: 3000,
            open: true,
            cors: true,
            proxy: {
                // 代理所有 /api 开头的请求
                '/api': {
                    target: env.VITE_API_BASE_URL || 'http://localhost:8080',
                    changeOrigin: true,
                    secure: false
                },
            }
        },

        // 构建配置
        build: {
            target: 'es2015',
            outDir: 'dist',
            assetsDir: 'assets',
            sourcemap: mode === 'development',
            minify: 'terser',

            rollupOptions: {
                output: {
                    // 分包策略
                    manualChunks: {
                        vendor: ['vue', 'vue-router'],
                        primevue: ['primevue/config', 'primevue/toastservice', 'primevue/confirmationservice'],
                        utils: ['crypto-js', 'ts-md5', 'js-md5']
                    },
                    // 资源文件命名
                    chunkFileNames: 'assets/js/[name]-[hash].js',
                    entryFileNames: 'assets/js/[name]-[hash].js',
                    assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
                }
            },

            // Terser 压缩配置
            terserOptions: {
                compress: {
                    drop_console: mode === 'production',
                    drop_debugger: mode === 'production'
                }
            }
        },

        // CSS 配置
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@use "@/assets/layout/variables/_common.scss";`
                }
            }
        },

        // 定义全局常量
        define: {
            __APP_VERSION__: JSON.stringify(process.env.npm_package_version || '1.0.0'),
            __BUILD_TIME__: JSON.stringify(new Date().toISOString())
        }
    };
});
